package org.becomingMd;

import java.io.File;
import java.sql.SQLException;
import java.util.List;

public class FileRecordingOperation {
    // 私有成员变量
    private ConDatabases conDatabases;

    // 构造方法中初始化
    public FileRecordingOperation() {
        try {
            this.conDatabases = new ConDatabases();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    public Boolean UpdateDatabaseFileRecords(File dir) throws SQLException {



        conDatabases.resetIsExisted();

        File[] files = dir.listFiles();
        assert files != null;
        if (files.length == 0) {
           return false;
        }


        for (File f : files) {
            if (f.isDirectory()) {
                // 递归获取子目录文件路径，并合并结果

               UpdateDatabaseFileRecords(f);
            } else {
                if(!conDatabases.isFileRecord(f.getAbsolutePath())){

                    String absolutePath = f.getAbsolutePath();
                    String fileName=f.getName();
                    int fileSize=(int)f.length();
                    String fileType= getFileExtension(fileName);
                    boolean isExisted=true;
                    boolean isSynced=true;
                    FileInfo fileInfo=new FileInfo(absolutePath,fileName,fileSize,fileType,isExisted,isSynced);
                    conDatabases.createFileRecord(fileInfo);
                }


            }
        }
        conDatabases.deleteNonExistedFiles();
        return true;
    }
    public List<File> getSyncedFile() throws SQLException {
        List<File> Files= conDatabases.getSyncedFilePaths();
        conDatabases.closeConnection();
        return Files;
    }



    public static String getFileExtension(String fileName) {
        int dotIndex = fileName.lastIndexOf('.');
        return (dotIndex == -1) ? "unknown" : fileName.substring(dotIndex + 1);
    }
}
